#include "devicestatus.h"
#include "ui_devicestatus.h"
#include <QFileDialog>
#include <QDebug>
#include <QSettings>
#include <QFileInfo>
#include <QTextCodec>
#include <QTime>
#include <QDate>

DeviceStatus::DeviceStatus(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::DeviceStatus)
{
    ui->setupUi(this);
    initialize();
}

DeviceStatus::~DeviceStatus()
{
    delete ui;
}

void DeviceStatus::initialize()
{
    decode.insert(0, "冷启动");
    decode.insert(1, "热启动");
    decode.insert(2, "硬件低故障");
    decode.insert(7, "地址冲突");
    decode.insert(8, "类型错误");

    ui->treeWidget->expandAll();
    connect(&socket, &QUdpSocket::readyRead, this, &on_socketRecive);
}


void DeviceStatus::on_pushButton_File_clicked()
{
    QString filename;
    QFileDialog dlg;

    if(ui->checkBox->isChecked()) {
        filename = dlg.getOpenFileName(this, "打开接口通信分机配置文件:", "./", "接口通信分机配置文件(*.iic)");
    } else {
        filename = dlg.getOpenFileName(this, "打开接口通信分机配置文件:", "./", "接口通信分机配置文件(*.ini)");
    }

    if(!filename.isEmpty()) {
        ui->lineEdit->setText(filename);
        readConfigrateFile(ui->lineEdit->text());
    }
}

void DeviceStatus::readConfigrateFile(QString filename)
{
    QFileInfo file(filename);

    if(file.exists()) {
//        QSettings *read = new QSettings(filename, QSettings::IniFormat);
//        read->setIniCodec("GBK");
//        qDebug() << read->childGroups();

        if(ui->checkBox->isChecked()) {
            parseAWXConfigrate();
        } else {
            parseConfigrate();
        }

    } else {
        ui->statusBar->showMessage(tr("文件不存在!"));
        ui->lineEdit->setText("");
    }
}

void DeviceStatus::parseConfigrate()
{
    QSettings cfg(ui->lineEdit->text(), QSettings::IniFormat);
    cfg.setIniCodec("GB2312");
//    cfg.beginGroup("数据格式设置");
    cfg.beginGroup("test");
    qDebug() << cfg.childKeys();
    cfg.endGroup();
}

void DeviceStatus::parseAWXConfigrate()
{

}

void DeviceStatus::on_pushButton_Listen_clicked()
{
    if(socket.isValid()) {
        socket.close();
        ui->pushButton_Listen->setText(tr("邦定监听端口"));
    } else {
        if(this->socket.bind(ui->spinBox->value())) {
            qDebug() << "邦定端口正功!";
            ui->pushButton_Listen->setText(tr("解邦监听端口"));
        } else {
            qDebug() << "邦定端口失败!";
        }
    }
}

void DeviceStatus::on_socketRecive()
{

    QByteArray ret;
    ret.resize(socket.pendingDatagramSize());
    QHostAddress ip;
    quint16 port;

    socket.readDatagram(ret.data(), socket.pendingDatagramSize(), &ip, &port);

    if(ret.isEmpty()) return;

    if(ret.at(0) != 0x00 || ret.at(1) != 0x11 || \
            ret.size() != 7 || ret.at(3) != 0x00 || ret.at(4) != 0x00) {
        ui->statusBar->showMessage("非正常的设备状自主帧");
        return;
    }

    ui->statusBar->showMessage(QString("收到开至:%1端口:%2的自主帧")\
                               .arg(ip.toString().replace("::ffff:", ""))\
                               .arg(QString::number(port)));

    ui->textEdit->append(QDate::currentDate().toString("yyyy/M/d ")+ QTime::currentTime().toString());
    quint8  code = *((quint8*) ret.mid(2).data());
    quint16 index = *((quint16 *) ret.mid(5).data());
    qDebug() << index << code;

    QString str;

    if(index == 0xFFFF) {
        str = "接口通信分机\t\t";
    } else {
        str = QString("设备接点[%1]\t").arg(QString::number(index),5);
    }

    str += this->decode.value((int)code,"未定义的状态类型");

    ui->textEdit->append(str);

}
